class NumberUtils { // NOTE: This calls the singleton 'NumberFormat'

	public static function formatNumber (i: Float) : String
	{ // TODO - remove this if haxe float has own
		var format: NumberFormat = NumberFormat.getInstance(null);
		return NumberUtils.format (
			i, 
			format.numDecimals, 
			format.isFixedNumDecimalsForced, 
			format.isDecimalSeparatorComma,
			format.isThousandSeparatorDisabled 
		);
	} 
	
	public static function formatNumberY2 (i: Float) : String
	{
		var format: NumberFormat = NumberFormat.getInstanceY2(null);
		return NumberUtils.format (i, 
			format.numDecimals, 
			format.isFixedNumDecimalsForced, 
			format.isDecimalSeparatorComma,
			format.isThousandSeparatorDisabled 
		);
	}	

	public static function format ( 
		i: Float
		, numDecimals: Int
		, isFixedNumDecimalsForced:Bool
		, isDecimalSeparatorComma:Bool
		, isThousandSeparatorDisabled:Bool 
	) : String
	{
		if ( Math.isNaN (numDecimals )) {
			numDecimals = 4;
		}
		
		// round the number down to the number of
		// decimals we want ( fixes the -1.11022302462516e-16 bug)
		var j:Float = Math.round(i*Math.pow(10,numDecimals))/Math.pow(10,numDecimals);
		
		var s:String = '';
		var num:Array<String>;
		if( j<0 )
			num = Std.string(-j).split('.');
		else
			num = Std.string(j).split('.');
		
		//trace ("a: " + num[0] + ":" + num[1]);
		var x:String = num[0];
		var pos: Int=0;
		var c: Int=0;

		var c : Int = x.length-1;
		while (c>-1)
		{
			if( pos%3==0 && s.length>0 )
			{
				s=','+s;
				pos=0;
			}
			pos++;
			s=x.substr(c,1)+s;
			c--;
		}

		if( num[1] != null ) { // TODO - This probably must be caught as an exception, test it!
			if (isFixedNumDecimalsForced){
				num[1] += "0000000000000000";
			}
			s += '.' + num[1].substr(0,numDecimals);
		} else {
			if (isFixedNumDecimalsForced && numDecimals>0){
				num[1] = "0000000000000000";
				s += '.'+ num[1].substr(0,numDecimals);			
			}
			
		}
			
		if( j<0 )
			s = '-'+s;
		
		if (isThousandSeparatorDisabled){
			s = StringTools.replace (s,",","");
		}
		
		if (isDecimalSeparatorComma) {
			s = toDecimalSeperatorComma(s);
		}			
		return s;
	}
	
	public static function toDecimalSeperatorComma (value:String) : String {
		var v : String = value;
		var t : Array<String>;
		var arr : Array<Array<String>> = [
			[".","|"]
			, [",","."]
			, ["|",","]
		];
		for (t in arr)
		{
			v = StringTools.replace(v,t[0],t[1]);
		}
		return v;
	}

}
